#include <net/can.h>
#include <pthread.h>

#define TIMEOUT_US         1000000

can can0, can1;
int j0=0, j1=0;

void* can0_recv(void *)
{
    int i = 0;

    for(i = 0; i < 256; i++) {
        struct can_frame frame;
        can0.recvframe(&frame);
        if (i == frame.data[0]) {
            j0++;
        }
        //printf("data %d\n", frame.data[0]);
    }
    //printf("can0_recv: j=%d\n", j0);
    return NULL;
}

void* can1_recv(void *)
{
    int i = 0;

    for(i = 0; i < 256; i++) {
        struct can_frame frame;
        can1.recvframe(&frame);
        if (i == frame.data[0]) {
            j1++;
        }
        //printf("data %d\n", frame.data[0]);
    }
    //printf("can1_recv: j=%d\n", j1);
    return NULL;
}

int main(void)
{
    pthread_t pid_can0_recv, pid_can1_recv;

    /* */
    if (-1 == can0.opendev("can0")) {
        perror("can0 opendev");
        return -1;
    }
    if (-1 == can1.opendev("can1")) {
        perror("can1 opendev");
        return -1;
    }

    /* */
    pthread_create(&pid_can0_recv, NULL, can0_recv, NULL);
    pthread_create(&pid_can1_recv, NULL, can1_recv, NULL);

    /* */
    for(int i = 0; i < 256; i++) {
        struct can_frame frame;
        frame.can_id = i;
        frame.can_dlc = 8;
        frame.data[0] = i;
        can0.sendframe(&frame);
    }
    usleep(TIMEOUT_US);
    if (256 == j1) {
        printf("can0 ---> can1 okay\n");
        pthread_join(pid_can1_recv, NULL);
    } else {
        printf("can0 ---> can1 error\n");
        pthread_cancel(pid_can1_recv);
    }
    /* */
    for(int i = 0; i < 256; i++) {
        struct can_frame frame;
        frame.can_id = i;
        frame.can_dlc = 8;
        frame.data[0] = i;
        can1.sendframe(&frame);
    }
    usleep(TIMEOUT_US);
    if (256 == j0) {
        printf("can1 ---> can0 okay\n");
        pthread_join(pid_can0_recv, NULL);
    } else {
        printf("can1 ---> can0 error\n");
        pthread_cancel(pid_can0_recv);
    }
    return 0;
}


